import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:yunim/utils/u_log.dart';

//╔══════════════════════════╗
//║ Author       : 贾恒飞
//║ Timer        : 2020/3/6
//║ Model        : yunim
//║ PackageName  : com.tencent.mm
//║ Node         : 微信表情
//╚══════════════════════════╝

///表情组件
class WeChatExpression extends StatelessWidget {
  ///一行表情数量
  final int crossAxisCount;

  //纵轴间距
  final double mainAxisSpacing;

  //横轴间距
  final double crossAxisSpacing;

  ///子Widget宽高比例
  final double childAspectRatio;

  ///大小比例,值的大小与表情的大小成反比
  final double bigSizeRatio;

  final CallClick _callClick;

  WeChatExpression(this._callClick,
      {this.crossAxisCount = 8,
      this.mainAxisSpacing = 2.0,
      this.crossAxisSpacing = 2.0,
      this.childAspectRatio = 1.0,
      this.bigSizeRatio = 8.0});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GridView.custom(
        shrinkWrap: true,
        padding: EdgeInsets.all(10.0),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: this.crossAxisCount,
          mainAxisSpacing: this.mainAxisSpacing,
          crossAxisSpacing: this.crossAxisSpacing,
        ),
        childrenDelegate: SliverChildBuilderDelegate((context, position) {
          return _getExpressionItemContainer(position);
        }, childCount: ExpressionData.EXPRESSION_SIZE),
      ),
    );
  }

  ///获取表情列表
  _getExpressionItemContainer(int index) {
    var expressionPath = ExpressionData.expressionPath[index];
    return AExpression(expressionPath, this.bigSizeRatio, this._callClick);
  }
}

///单个表情
class AExpression extends StatelessWidget {
  Expression expression;

  ///大小比例,值的大小与表情的大小成反比
  final double bigSizeRatio;

  final CallClick _callClick;

  AExpression(this.expression, this.bigSizeRatio, this._callClick);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FlatButton(
        padding: EdgeInsets.all(bigSizeRatio),
        onPressed: () {
          _callClick(expression);
        },
        child: Image.asset(
          ExpressionData.basePath + expression.path,
        ),
      ),
    );
  }
}

///点击之后
typedef void CallClick(Expression expression);

///表情对象
class Expression {
  final String name;
  final String path;

  ///标识是否是emoji表情,true是,默认false
  final bool isEmoji;

  Expression(this.name, this.path, {this.isEmoji = false});
}

///数据类
class ExpressionData {
  ///基础路径
  static String basePath = "assets/expression/";

  ///表情路径
  static final List<Expression> expressionPath = [
    Expression('微笑', 'emoj_1.png'),
    Expression('吐舌', 'emoj_2.png'),
    Expression('大笑', 'emoj_3.png'),
    Expression('挤眼', 'emoj_4.png'),
    Expression('怪笑', 'emoj_5.png'),
    Expression('尬笑', 'emoj_6.png'),
    Expression('瞪眼', 'emoj_7.png'),
    Expression('嘿嘿', 'emoj_8.png'),
    Expression('开心', 'emoj_9.png'),
    Expression('哦哦', 'emoj_10.png'),
    Expression('眼镜', 'emoj_11.png'),
    Expression('冷汗', 'emoj_12.png'),
    Expression('咬你', 'emoj_13.png'),
    Expression('就这', 'emoj_14.png'),
    Expression('搞怪', 'emoj_15.png'),
    Expression('失落', 'emoj_16.png'),
    Expression('得意', 'emoj_17.png'),
    Expression('笑哭', 'emoj_18.png'),
    Expression('生气', 'emoj_19.png'),
    Expression('明白', 'emoj_20.png'),
    Expression('星眼', 'emoj_21.png'),
    Expression('惊奇', 'emoj_22.png'),
    Expression('斜眼', 'emoj_23.png'),
    Expression('笑哭2', 'emoj_24.png'),
    Expression('撇嘴', 'emoj_25.png'),
    Expression('撇嘴2', 'emoj_26.png'),
    Expression('笑2', 'emoj_27.png'),
    Expression('哦1', 'emoj_28.png'),
    Expression('啥啊', 'emoj_29.png'),
    Expression('表1', 'emoj_30.png'),
    Expression('表2', 'emoj_31.png'),
    Expression('表3', 'emoj_32.png'),
    Expression('表4', 'emoj_33.png'),
    Expression('表5', 'emoj_34.png'),
    Expression('表6', 'emoj_35.png'),
    Expression('表7', 'emoj_36.png'),
    Expression('表8', 'emoj_37.png'),
    Expression('表9', 'emoj_38.png'),
    Expression('表10', 'emoj_39.png'),
    Expression('表11', 'emoj_40.png'),
    Expression('表12', 'emoj_d1.png'),
    Expression('表13', 'emoj_d2.png'),
    Expression('表13', 'emoj_d2.png'),
    Expression('表14', 'emoj_d3.png'),
    Expression('表15', 'emoj_d4.png'),
    Expression('表16', 'emoj_d5.png'),
    Expression('表17', 'emoj_d6.png'),
    Expression('表18', 'emoj_d7.png'),
  ];

  ///kv
  static final Map<String, String> expressionKV = {};

  ///初始化
  static void init() {
    for (var value in expressionPath) {
      expressionKV[value.name] = value.path;
    }
  }

  ///格式化消息
  static String format(String msg) {}

  ///表情总长度
  // ignore: non_constant_identifier_names
  static final int EXPRESSION_SIZE = expressionPath.length;
}

class ExpressionText extends StatelessWidget {
  final String _text;
  final TextStyle _textStyle;
  ExpressionText(this._text, this._textStyle, {Key key}) : super(key: key);
  List<InlineSpan> stack = [];
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text.rich(TextSpan(children: _getContent(_text))),
    );
  }

  _getContent(content) {
    if (content.contains('[emoj_')) {
      int start = content.indexOf('[emoj_');
      int end = content.indexOf(']') + 1;
      String textContent = content.substring(0, start);
      String icoConent = content.substring(start + 1, end - 1);
      String surplus = content.substring(end, content.length);
      if (!textContent.isEmpty) {
        stack.add(TextSpan(
          text: textContent,
          style: _textStyle,
        ));
      }
      stack.add(WidgetSpan(
        child: Image.asset(
          'assets/expression/${icoConent}.png',
          alignment: Alignment.center,
          width: 30.0,
          height: 30.0,
          fit: BoxFit.cover,
        ),
        alignment: PlaceholderAlignment.middle,
      ));
      _getContent(surplus);
    } else {
      stack.add(TextSpan(
        text: content,
        style: _textStyle,
      ));
    }
    return stack;
  }
}

///带有表情的文本
///备注:这里本想用自定义View直接写,因为项目太紧也没仔细研究,
///如果有人写出来也麻烦copy我一份学习学习
///这里就直接用Wrap配合Text与Image直接拼接的消息,测试了一下也不会卡;
// class ExpressionText extends StatelessWidget {
//   final String _text;
//   final TextStyle _textStyle;

//   //最大行数,默认-1,不限制
//   final int maxLine;

//   const ExpressionText(this._text, this._textStyle,
//       {Key key, this.maxLine = -1})
//       : super(key: key);

//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       child: (maxLine > 0)
//           ? Text.rich(
//               TextSpan(
//                 children: _getContent(),
//               ),
//               maxLines: maxLine,
//             )
//           : Text.rich(
//               TextSpan(
//                 children: _getContent(),
//               ),
//             ),
//     );
//   }

//   ///使用正则解析表情文本,使用了Text.rich替换掉了Wrap
//   _getContent() {
//     if (ExpressionData.expressionKV.length == 0) {
//       ExpressionData.init();
//     }
//     List<InlineSpan> stack = [];

//     List<int> indexList = [];

//     //正则校验是否含有表情
//     RegExp exp = new RegExp(r'\[.{1,4}?\]');
//     if (exp.hasMatch(_text)) {
//       var array = exp.allMatches(_text).toList();
//       for (RegExpMatch r in array) {
//         var substring = _text.substring(r.start, r.end);
//         var select = substring.substring(1, substring.length - 1);
//         if (ExpressionData.expressionKV.containsKey(select)) {
//           indexList.add(r.start);
//           indexList.add(r.end);
//         }
//       }
//       int afterX = 0;
//       for (int x = 0; x < indexList.length; x = x + 2) {
//         int y = x + 1;
//         var indexX = indexList[x];
//         var indexY = indexList[y];
//         var substring = _text.substring(afterX, indexX);
//         afterX = indexY;
//         stack.add(TextSpan(
//           text: substring,
//           style: _textStyle,
//         ));
//         var xy = _text.substring(indexX, indexY);
//         var selectXy = xy.substring(1, xy.length - 1);
//         var expressionKV = ExpressionData.expressionKV[selectXy];
//         stack.add(WidgetSpan(
//           child: Image.asset(
//             'assets/expression/$expressionKV',
//             width: 20.0,
//             height: 20.0,
//           ),
//         ));
//       }
//     } else {
//       stack.add(TextSpan(
//         text: _text,
//         style: _textStyle,
//       ));
//     }

//     return stack;
//   }
// }
